#!/bin/bash
set -ex

source ./common.sh

cur_dir=$(dirname "$(readlink -f "$0")")

install_harbor() {
    harbor_package=$(find "$TARGET_DIR" -type f -name "harbor.tgz" | sort | tail -n 1)

    if [ -z "$harbor_package" ]; then
        echo "没有找到 Harbor 安装包。"
        return 1
    fi

    if [ -d "$HARBOR_DIR" ]; then
        echo "清理旧配置 ..."
        echo "$HOST_PASSWORD" | sudo rm -rf "$HARBOR_DIR"
        # TODO 增加按需删除日志和数据
        echo "$HOST_PASSWORD" | sudo rm -rf "$HARBOR_DATA"
        echo "$HOST_PASSWORD" | sudo rm -rf "$HARBOR_LOG"
    fi

    echo "找到 Harbor 安装包，开始安装 Harbor..."
    tar xzf "$harbor_package" -C "$TARGET_DIR"

    if [ ! -d "$HARBOR_DIR" ]; then
        echo "Harbor 安装失败。"
        return 1
    else
        mkdir -p "$HARBOR_DATA"
        mkdir -p "$HARBOR_LOG"
        pushd "$HARBOR_DIR"
        cp harbor.yml.tmpl harbor.yml
        hostname=$(yq e '.hostname' "$CONFIG_FILE")
        yq e ".hostname = \"$hostname\"" -i harbor.yml
        harbor_admin_password=$(yq e '.harbor_admin_password' "$CONFIG_FILE")
        yq e ".harbor_admin_password = \"$harbor_admin_password\"" -i harbor.yml
        yq e ".data_volume = \"$HARBOR_DATA\"" -i harbor.yml
        yq e ".log.local.location = \"$HARBOR_LOG\"" -i harbor.yml
        # TODO 暂时不配置 https
        yq e 'del(.https)' -i harbor.yml
        echo "$HOST_PASSWORD" | sudo ./install.sh
        popd
        echo "Harbor 安装成功。"
    fi

    # TODO 添加 harbor 安装后的验证
}

pushd "$cur_dir"
preset
if [ ! -d "$TARGET_DIR" ]; then
    mkdir -p "$TARGET_DIR"
fi
found_files=$(find "$TARGET_DIR" -type f -name "harbor.tgz")
if [ -z "$found_files" ]; then
    yq e '.files[]' "$CONFIG_FILE" | while IFS= read -r item; do
        file_name=$(echo "$item" | yq e '.filename' -)
        file_url=$(echo "$item" | yq e '.fileUrl' -)
        md5_url=$(echo "$item" | yq e '.md5Url' -)
        echo "$file_name" "$file_url" "$md5_url"
        download_and_verify "$file_name" "$file_url" "$md5_url" "$TARGET_DIR"
    done
fi
install_harbor
popd
